{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Using Functions" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" }, "tags": [ "remove-cell" ] }, "source": [ "**CS1302 Introduction to Computer Programming**\n", "___" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2020-11-27T11:20:04.656873Z", "start_time": "2020-11-27T11:20:04.651575Z" }, "slideshow": { "slide_type": "fragment" }, "tags": [ "remove-cell" ] }, "outputs": [], "source": [ "%reload_ext mytutor" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Motivation" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "**How to reuse code so we can write less?**" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Writing a loop is a simple way of code reuse because a piece of code is executed multiple times, once for each iteration." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "*Code reuse* gives the code an elegant *structure* that\n", "- can be executed efficiently by a computer, and\n", "- *interpreted* easily by a programmer." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "**How to repeat execution at different times, in different programs, and in slightly different ways?**" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Functions" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "**How to calculate the logarithm?**" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "There is no arithmetic operator for logarithm. \n", "Do we have to implement it ourselves?" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "We can use the function `log` from the [`math` *module*](https://docs.python.org/3/library/math.html):" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:36:42.539302Z", "start_time": "2020-09-26T10:36:42.531086Z" }, "slideshow": { "slide_type": "-" } }, "outputs": [ { "data": { "text/plain": [ "8.0" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from math import log\n", "\n", "log(256, 2) # log base 2 of 256" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "The above computes the base-$2$ logarithm, $\\log_2(256)$. Like functions in mathematics, a computer function `log` \n", "- is *called/invoked* with some input *arguments* `(256, 2)` following the function, and\n", "- *returns* an output value computed from the input arguments." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:37:30.410063Z", "start_time": "2020-09-26T10:37:30.402747Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "(True, False)" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# A function is callable while an integer is not\n", "callable(log), callable(1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Unlike mathematical functions:\n", "- A python function may require no arguments, but we still need to call it with `()`. " ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:37:52.209981Z", "start_time": "2020-09-26T10:37:49.292575Z" }, "scrolled": true, "slideshow": { "slide_type": "-" }, "tags": [ "remove-output" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] }, { "data": { "text/plain": [ "''" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "input()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- A python function may have *side effects* and return the value `None`." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:38:06.459546Z", "start_time": "2020-09-26T10:38:06.454332Z" }, "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "None of type \n" ] } ], "source": [ "x = print()\n", "print(x, \"of type\", type(x))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "An argument of a function call can be any expression." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:38:55.805698Z", "start_time": "2020-09-26T10:38:50.415718Z" }, "slideshow": { "slide_type": "-" }, "tags": [ "remove-output" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "1st input: 1 2nd input 2\n" ] } ], "source": [ "print(\"1st input:\", input(), \"2nd input\", input())" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Note that\n", "- the argument can also be a function call like function composition in mathematics. \n", "- Before a function call is executed, its arguments are evaluated first from left to right." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**Why not implement logarithm yourself?**" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- The function from standard library is efficiently implemented and thoroughly tested/documented.\n", "- Knowing what a function does is often insufficient for an efficient implementation. \n", " (See [how to calculate logarithm](https://en.wikipedia.org/wiki/Logarithm#Calculation) as an example.)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Indeed, the `math` library does not implement `log` itself:\n", "> **CPython implementation detail:** The `math` module consists mostly of thin *wrappers* around the platform C math library functions. - [pydoc last paragraph](https://docs.python.org/3/library/math.html)\n", "\n", "(See the [source code wrapper for `log`](https://github.com/python/cpython/blob/457d4e97de0369bc786e363cb53c7ef3276fdfcd/Modules/mathmodule.c#L731).) " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**Exercise** What is a function in programming?" ] }, { "cell_type": "markdown", "metadata": { "nbgrader": { "grade": true, "grade_id": "what-is-a-function", "locked": false, "points": 0, "schema_version": 3, "solution": true, "task": false }, "slideshow": { "slide_type": "-" } }, "source": [ "- A function is a structure that allows a piece of code to be reused in a program. \n", "- A function can adapt its computations to different situations using input arguments. " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Import Functions from Modules" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "**How to import functions?**" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "We can use the [`import` statement](https://docs.python.org/3/reference/simple_stmts.html#import) to import multiple functions into the program *global frame*." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:41:22.594751Z", "start_time": "2020-09-26T10:41:22.588506Z" }, "slideshow": { "slide_type": "-" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%mytutor -h 300\n", "from math import ceil, log10\n", "\n", "x = 1234\n", "print(\"Number of digits of x:\", ceil(log10(x)))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "The above imports both the functions `log10` and `ceil` from `math` to compute the number $\\lceil \\log_{10}(x)\\rceil$ of digits of a *strictly positive* integer $x$." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**How to import all functions from a library?**" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:42:54.301642Z", "start_time": "2020-09-26T10:42:54.293055Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%mytutor -h 300\n", "from math import * # import all except names starting with an underscore\n", "\n", "print(\"{:.2f}, {:.2f}, {:.2f}\".format(sin(pi / 6), cos(pi / 3), tan(pi / 4)))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "The above uses the wildcard `*` to import ([nearly](https://docs.python.org/3/tutorial/modules.html#more-on-modules)) all the functions/variables provided in `math`." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "**What if different packages define the same function?**" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:44:06.443022Z", "start_time": "2020-09-26T10:44:06.434362Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%mytutor -h 300\n", "print(\"{}\".format(pow(-1, 2)))\n", "print(\"{:.2f}\".format(pow(-1, 1 / 2)))\n", "from math import *\n", "\n", "print(\"{}\".format(pow(-1, 2)))\n", "print(\"{:.2f}\".format(pow(-1, 1 / 2)))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- The function `pow` imported from `math` overwrites the built-in function `pow`. \n", "- Unlike the built-in function, `pow` from `math` returns only floats but not integers or complex numbers. \n", "- We say that the import statement *polluted the namespace of the global frame* and caused a *name collision*. " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**How to avoid name collisions?**" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:45:35.988045Z", "start_time": "2020-09-26T10:45:35.981943Z" }, "slideshow": { "slide_type": "-" } }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%mytutor -h 250\n", "import math\n", "\n", "print(\"{:.2f}, {:.2f}\".format(math.pow(-1, 2), pow(-1, 1 / 2)))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "We can use the full name (*fully-qualified name*) `math.pow` prefixed with the module name (and possibly package names containing the module)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**Can we shorten a name?**" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "The name of a library can be very long and there can be a hierarchical structure as well. \n", "E.g., to plot a sequence using `pyplot` module from `matplotlib` package:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2020-09-14T11:29:37.606167Z", "start_time": "2020-09-14T11:29:37.352615Z" }, "slideshow": { "slide_type": "-" } }, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYQAAAEWCAYAAABmE+CbAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Z1A+gAAAACXBIWXMAAAsTAAALEwEAmpwYAAAZz0lEQVR4nO3dfbRddX3n8ffHcNFU1NjmjoTwEMdFqSLV0AwPpbWMteWhrJJFbYu1IPQBsDpTOw4ucTrartpFZzF9UHFIabWUpQVdLc1iaZiUtSwV2vIQIIACmUlthTw4XKEJRO6iEL/zx/lFTw7nJvcm95xzb/J+rXVW9t6/39n7u8/v5nzu2Xvfs1NVSJL0klEXIEmaGwwESRJgIEiSGgNBkgQYCJKkxkCQJAEGgjRSSV6T5MtJnkny+yOu5bokHx1lDRqtQ0ZdgOa/JLcBbwIOr6rnRlzOfHMJ8E3gleUfBWnE/ISg/ZJkGfCjQAE/Pdpq5qVjgIcPtDBIsmDUNWjmDATtrwuBO4HrgHftqWOSi5J8rR0e+eck7+xq+6UkjyT51yRrkxzT1fYTSR5Nsj3J1Un+LsmvtLbfSvKZrr7LklSSQ9r8q5J8KsnWJJuTfHTXm1Wr544k/7Nt95+TnNW1ru9N8mdJtrT21V1t5yRZn2Rbkn9I8oN72O8fTnJPq/+eJD/clu96zT6QZEeSt/V57nVJPpnki+11uyvJ6/rta1t2W9drc1GSv0/yh63Or7VaLkryeJInkvSO2eIkt7Zt/V3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dV9vmrWx+RA/oSwCTiqa/5IYMs+9JkL9lpnVT296yNmde5QN5Zk8fBKnDXzZUz2aj6NSZIxOm+gn62qm/p0mTfjsrd9mU/jAlBV24DbgDN7mmZ9TA7kQLgHODbJa5McCpwP3NzT52bgwna2/hRge1VtHXah07DXfUlyeJK06ZPojO2TQ690/82XMdmr+TImrcZPAY9U1R9M0W1ejMt09mU+jEuS8fbJgCQLgbcBj/Z0m/UxOWAPGVXVC0neC6ylc5XOp6vqq0kua+2r6Nzn+WxgI/AscPGo6t2Tae7L24F3J3kBmATOr3YpwlyS5AY6V3ksTrIJ+AidE2bzakxgWvsyL8YEOA24AHioHbMG+BBwNMy7cZnOvsyHcVkC/HmSBXQC6/NV9YVBv3/51RWSJODAPmQkSZoBA0GSBBgIkqTGQJAkAQaCJKkxECRJgIEgSWoMBGkWJfnrJB9NcnuSbyR526hrkqbLQJBm1xuBbVX1o8CvAe8ccT3StBkI0ixJ8j3Aq4A/bIsOAbaNrCBphgwEafYcD9zbvrYY4AeBvrfXlOYiA0GaPW8E1nfN/yDw4GhKkWbOQJBmzwnsHghvxE8Imkf8tlNJEuAnBElSYyBIkgADQZLUGAiSJMBAkCQ1BoIkCTAQJEnN/wf6Q+GyKY84ZQAAAABJRU5ErkJggg==\n", "text/plain": [ "
" ] }, "metadata": { "needs_background": "light" }, "output_type": "display_data" } ], "source": [ "%matplotlib inline\n", "import matplotlib.pyplot\n", "\n", "matplotlib.pyplot.stem([4, 3, 2, 1])\n", "matplotlib.pyplot.ylabel(r\"$x_n$\")\n", "matplotlib.pyplot.xlabel(r\"$n$\")\n", "matplotlib.pyplot.title(\"A sequence of numbers\")\n", "matplotlib.pyplot.show()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "It is common to rename `matplotlib.pyplot` as `plt`:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2020-09-17T02:21:42.115792Z", "start_time": "2020-09-17T02:21:41.849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ylc5XOp6vqq0kua+2r6Nzn+WxgI/AscPGo6t2Tae7L24F3J3kBmATOr3YpwlyS5AY6V3ksTrIJ+AidE2bzakxgWvsyL8YEOA24AHioHbMG+BBwNMy7cZnOvsyHcVkC/HmSBXQC6/NV9YVBv3/51RWSJODAPmQkSZoBA0GSBBgIkqTGQJAkAQaCJKkxECRJgIEgSWoMBGkWJfnrJB9NcnuSbyR526hrkqbLQJBm1xuBbVX1o8CvAe8ccT3StBkI0ixJ8j3Aq4A/bIsOAbaNrCBphgwEafYcD9zbvrYY4AeBvrfXlOYiA0GaPW8E1nfN/yDw4GhKkWbOQJBmzwnsHghvxE8Imkf8tlNJEuAnBElSYyBIkgADQZLUGAiSJMBAkCQ1BoIkCTAQJEnN/wf6Q+GyKY84ZQAAAABJRU5ErkJggg==\n", "text/plain": [ "
" ] }, "metadata": { "needs_background": "light" }, "output_type": "display_data" } ], "source": [ "import matplotlib.pyplot as plt\n", "\n", "plt.stem([4, 3, 2, 1])\n", "plt.ylabel(r\"$x_n$\")\n", "plt.xlabel(r\"$n$\")\n", "plt.title(\"A sequence of numbers\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "We can also rename a function as we import it to avoid name collision:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "ExecuteTime": { "end_time": "2020-09-14T12:17:46.823708Z", "start_time": "2020-09-14T12:17:46.815682Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "(4.0, 4)" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from math import pow as fpow\n", "\n", "fpow(2, 2), pow(2, 2)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**Exercise** What is wrong with the following code?" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:49:46.071860Z", "start_time": "2020-09-26T10:49:46.001859Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "AttributeError", "evalue": "'int' object has no attribute 'pow'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_232/251642800.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mmath\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mm\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mfor\u001b[0m \u001b[0mm\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mm\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpow\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mm\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m: 'int' object has no attribute 'pow'" ] } ], "source": [ "import math as m\n", "\n", "for m in range(5):\n", " m.pow(m, 2)" ] }, { "cell_type": "markdown", "metadata": { "nbgrader": { "grade": true, "grade_id": "name-conflict", "locked": false, "points": 0, "schema_version": 3, "solution": true, "task": false }, "slideshow": { "slide_type": "-" } }, "source": [ "There is a name collision: `m` is assigned to an integer in the for loop and so it is no longer the module `math` when calling `m.pow`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise** Use the `randint` function from `random` to simulate the rolling of a die, by printing a random integer from 1 to 6. " ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "ExecuteTime": { "end_time": "2020-09-17T02:38:32.718543Z", "start_time": "2020-09-17T02:38:32.711578Z" }, "nbgrader": { "grade": true, "grade_id": "random", "locked": false, "points": 0, "schema_version": 3, "solution": true, "task": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n" ] } ], "source": [ "import random\n", "\n", "print(random.randint(1, 6))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Built-in Functions" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "**How to learn more about a function such as `randint`?**" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "There is a built-in function `help` for showing the *docstring* (documentation string). " ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:51:54.624111Z", "start_time": "2020-09-26T10:51:54.619242Z" }, "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on method randint in module random:\n", "\n", "randint(a, b) method of random.Random instance\n", " Return random integer in range [a, b], including both end points.\n", "\n" ] } ], "source": [ "import random\n", "\n", "help(random.randint) # random must be imported before" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:52:06.890625Z", "start_time": "2020-09-26T10:52:06.875177Z" }, "scrolled": true, "slideshow": { "slide_type": "-" }, "tags": [ "output_scroll", "remove-output" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on module random:\n", "\n", "NAME\n", " random - Random variable generators.\n", "\n", "MODULE REFERENCE\n", " https://docs.python.org/3.8/library/random\n", " \n", " The following documentation is automatically generated from the Python\n", " source files. It may be incomplete, incorrect or include features that\n", " are considered implementation detail and may vary between Python\n", " implementations. When in doubt, consult the module reference at the\n", " location listed above.\n", "\n", "DESCRIPTION\n", " integers\n", " --------\n", " uniform within range\n", " \n", " sequences\n", " ---------\n", " pick random element\n", " pick random sample\n", " pick weighted random sample\n", " generate random permutation\n", " \n", " distributions on the real line:\n", " ------------------------------\n", " uniform\n", " triangular\n", " normal (Gaussian)\n", " lognormal\n", " negative exponential\n", " gamma\n", " beta\n", " pareto\n", " Weibull\n", " \n", " distributions on the circle (angles 0 to 2pi)\n", " ---------------------------------------------\n", " circular uniform\n", " von Mises\n", " \n", " General notes on the underlying Mersenne Twister core generator:\n", " \n", " * The period is 2**19937-1.\n", " * It is one of the most extensively tested generators in existence.\n", " * The random() method is implemented in C, executes in a single Python step,\n", " and is, therefore, threadsafe.\n", "\n", "CLASSES\n", " _random.Random(builtins.object)\n", " Random\n", " SystemRandom\n", " \n", " class Random(_random.Random)\n", " | Random(x=None)\n", " | \n", " | Random number generator base class used by bound module functions.\n", " | \n", " | Used to instantiate instances of Random to get generators that don't\n", " | share state.\n", " | \n", " | Class Random can also be subclassed if you want to use a different basic\n", " | generator of your own devising: in that case, override the following\n", " | methods: random(), seed(), getstate(), and setstate().\n", " | Optionally, implement a getrandbits() method so that randrange()\n", " | can cover arbitrarily large ranges.\n", " | \n", " | Method resolution order:\n", " | Random\n", " | _random.Random\n", " | builtins.object\n", " | \n", " | Methods defined here:\n", " | \n", " | __getstate__(self)\n", " | # Issue 17489: Since __reduce__ was defined to fix #759889 this is no\n", " | # longer called; we leave it here because it has been here since random was\n", " | # rewritten back in 2001 and why risk breaking something.\n", " | \n", " | __init__(self, x=None)\n", " | Initialize an instance.\n", " | \n", " | Optional argument x controls seeding, as for Random.seed().\n", " | \n", " | __reduce__(self)\n", " | Helper for pickle.\n", " | \n", " | __setstate__(self, state)\n", " | \n", " | betavariate(self, alpha, beta)\n", " | Beta distribution.\n", " | \n", " | Conditions on the parameters are alpha > 0 and beta > 0.\n", " | Returned values range between 0 and 1.\n", " | \n", " | choice(self, seq)\n", " | Choose a random element from a non-empty sequence.\n", " | \n", " | choices(self, population, weights=None, *, cum_weights=None, k=1)\n", " | Return a k sized list of population elements chosen with replacement.\n", " | \n", " | If the relative weights or cumulative weights are not specified,\n", " | the selections are made with equal probability.\n", " | \n", " | expovariate(self, lambd)\n", " | Exponential distribution.\n", " | \n", " | lambd is 1.0 divided by the desired mean. It should be\n", " | nonzero. (The parameter would be called \"lambda\", but that is\n", " | a reserved word in Python.) Returned values range from 0 to\n", " | positive infinity if lambd is positive, and from negative\n", " | infinity to 0 if lambd is negative.\n", " | \n", " | gammavariate(self, alpha, beta)\n", " | Gamma distribution. Not the gamma function!\n", " | \n", " | Conditions on the parameters are alpha > 0 and beta > 0.\n", " | \n", " | The probability distribution function is:\n", " | \n", " | x ** (alpha - 1) * math.exp(-x / beta)\n", " | pdf(x) = --------------------------------------\n", " | math.gamma(alpha) * beta ** alpha\n", " | \n", " | gauss(self, mu, sigma)\n", " | Gaussian distribution.\n", " | \n", " | mu is the mean, and sigma is the standard deviation. This is\n", " | slightly faster than the normalvariate() function.\n", " | \n", " | Not thread-safe without a lock around calls.\n", " | \n", " | getstate(self)\n", " | Return internal state; can be passed to setstate() later.\n", " | \n", " | lognormvariate(self, mu, sigma)\n", " | Log normal distribution.\n", " | \n", " | If you take the natural logarithm of this distribution, you'll get a\n", " | normal distribution with mean mu and standard deviation sigma.\n", " | mu can have any value, and sigma must be greater than zero.\n", " | \n", " | normalvariate(self, mu, sigma)\n", " | Normal distribution.\n", " | \n", " | mu is the mean, and sigma is the standard deviation.\n", " | \n", " | paretovariate(self, alpha)\n", " | Pareto distribution. alpha is the shape parameter.\n", " | \n", " | randint(self, a, b)\n", " | Return random integer in range [a, b], including both end points.\n", " | \n", " | randrange(self, start, stop=None, step=1, _int=)\n", " | Choose a random item from range(start, stop[, step]).\n", " | \n", " | This fixes the problem with randint() which includes the\n", " | endpoint; in Python this is usually not what you want.\n", " | \n", " | sample(self, population, k)\n", " | Chooses k unique random elements from a population sequence or set.\n", " | \n", " | Returns a new list containing elements from the population while\n", " | leaving the original population unchanged. The resulting list is\n", " | in selection order so that all sub-slices will also be valid random\n", " | samples. This allows raffle winners (the sample) to be partitioned\n", " | into grand prize and second place winners (the subslices).\n", " | \n", " | Members of the population need not be hashable or unique. If the\n", " | population contains repeats, then each occurrence is a possible\n", " | selection in the sample.\n", " | \n", " | To choose a sample in a range of integers, use range as an argument.\n", " | This is especially fast and space efficient for sampling from a\n", " | large population: sample(range(10000000), 60)\n", " | \n", " | seed(self, a=None, version=2)\n", " | Initialize internal state from hashable object.\n", " | \n", " | None or no argument seeds from current time or from an operating\n", " | system specific randomness source if available.\n", " | \n", " | If *a* is an int, all bits are used.\n", " | \n", " | For version 2 (the default), all of the bits are used if *a* is a str,\n", " | bytes, or bytearray. For version 1 (provided for reproducing random\n", " | sequences from older versions of Python), the algorithm for str and\n", " | bytes generates a narrower range of seeds.\n", " | \n", " | setstate(self, state)\n", " | Restore internal state from object returned by getstate().\n", " | \n", " | shuffle(self, x, random=None)\n", " | Shuffle list x in place, and return None.\n", " | \n", " | Optional argument random is a 0-argument function returning a\n", " | random float in [0.0, 1.0); if it is the default None, the\n", " | standard random.random will be used.\n", " | \n", " | triangular(self, low=0.0, high=1.0, mode=None)\n", " | Triangular distribution.\n", " | \n", " | Continuous distribution bounded by given lower and upper limits,\n", " | and having a given mode value in-between.\n", " | \n", " | http://en.wikipedia.org/wiki/Triangular_distribution\n", " | \n", " | uniform(self, a, b)\n", " | Get a random number in the range [a, b) or [a, b] depending on rounding.\n", " | \n", " | vonmisesvariate(self, mu, kappa)\n", " | Circular data distribution.\n", " | \n", " | mu is the mean angle, expressed in radians between 0 and 2*pi, and\n", " | kappa is the concentration parameter, which must be greater than or\n", " | equal to zero. If kappa is equal to zero, this distribution reduces\n", " | to a uniform random angle over the range 0 to 2*pi.\n", " | \n", " | weibullvariate(self, alpha, beta)\n", " | Weibull distribution.\n", " | \n", " | alpha is the scale parameter and beta is the shape parameter.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Class methods defined here:\n", " | \n", " | __init_subclass__(**kwargs) from builtins.type\n", " | Control how subclasses generate random integers.\n", " | \n", " | The algorithm a subclass can use depends on the random() and/or\n", " | getrandbits() implementation available to it and determines\n", " | whether it can generate random integers from arbitrarily large\n", " | ranges.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes defined here:\n", " | \n", " | VERSION = 3\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from _random.Random:\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | getrandbits(self, k, /)\n", " | getrandbits(k) -> x. Generates an int with k random bits.\n", " | \n", " | random(self, /)\n", " | random() -> x in the interval [0, 1).\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods inherited from _random.Random:\n", " | \n", " | __new__(*args, **kwargs) from builtins.type\n", " | Create and return a new object. See help(type) for accurate signature.\n", " \n", " class SystemRandom(Random)\n", " | SystemRandom(x=None)\n", " | \n", " | Alternate random number generator using sources provided\n", " | by the operating system (such as /dev/urandom on Unix or\n", " | CryptGenRandom on Windows).\n", " | \n", " | Not available on all systems (see os.urandom() for details).\n", " | \n", " | Method resolution order:\n", " | SystemRandom\n", " | Random\n", " | _random.Random\n", " | builtins.object\n", " | \n", " | Methods defined here:\n", " | \n", " | getrandbits(self, k)\n", " | getrandbits(k) -> x. Generates an int with k random bits.\n", " | \n", " | getstate = _notimplemented(self, *args, **kwds)\n", " | \n", " | random(self)\n", " | Get the next random number in the range [0.0, 1.0).\n", " | \n", " | seed(self, *args, **kwds)\n", " | Stub method. Not used for a system random number generator.\n", " | \n", " | setstate = _notimplemented(self, *args, **kwds)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from Random:\n", " | \n", " | __getstate__(self)\n", " | # Issue 17489: Since __reduce__ was defined to fix #759889 this is no\n", " | # longer called; we leave it here because it has been here since random was\n", " | # rewritten back in 2001 and why risk breaking something.\n", " | \n", " | __init__(self, x=None)\n", " | Initialize an instance.\n", " | \n", " | Optional argument x controls seeding, as for Random.seed().\n", " | \n", " | __reduce__(self)\n", " | Helper for pickle.\n", " | \n", " | __setstate__(self, state)\n", " | \n", " | betavariate(self, alpha, beta)\n", " | Beta distribution.\n", " | \n", " | Conditions on the parameters are alpha > 0 and beta > 0.\n", " | Returned values range between 0 and 1.\n", " | \n", " | choice(self, seq)\n", " | Choose a random element from a non-empty sequence.\n", " | \n", " | choices(self, population, weights=None, *, cum_weights=None, k=1)\n", " | Return a k sized list of population elements chosen with replacement.\n", " | \n", " | If the relative weights or cumulative weights are not specified,\n", " | the selections are made with equal probability.\n", " | \n", " | expovariate(self, lambd)\n", " | Exponential distribution.\n", " | \n", " | lambd is 1.0 divided by the desired mean. It should be\n", " | nonzero. (The parameter would be called \"lambda\", but that is\n", " | a reserved word in Python.) Returned values range from 0 to\n", " | positive infinity if lambd is positive, and from negative\n", " | infinity to 0 if lambd is negative.\n", " | \n", " | gammavariate(self, alpha, beta)\n", " | Gamma distribution. Not the gamma function!\n", " | \n", " | Conditions on the parameters are alpha > 0 and beta > 0.\n", " | \n", " | The probability distribution function is:\n", " | \n", " | x ** (alpha - 1) * math.exp(-x / beta)\n", " | pdf(x) = --------------------------------------\n", " | math.gamma(alpha) * beta ** alpha\n", " | \n", " | gauss(self, mu, sigma)\n", " | Gaussian distribution.\n", " | \n", " | mu is the mean, and sigma is the standard deviation. This is\n", " | slightly faster than the normalvariate() function.\n", " | \n", " | Not thread-safe without a lock around calls.\n", " | \n", " | lognormvariate(self, mu, sigma)\n", " | Log normal distribution.\n", " | \n", " | If you take the natural logarithm of this distribution, you'll get a\n", " | normal distribution with mean mu and standard deviation sigma.\n", " | mu can have any value, and sigma must be greater than zero.\n", " | \n", " | normalvariate(self, mu, sigma)\n", " | Normal distribution.\n", " | \n", " | mu is the mean, and sigma is the standard deviation.\n", " | \n", " | paretovariate(self, alpha)\n", " | Pareto distribution. alpha is the shape parameter.\n", " | \n", " | randint(self, a, b)\n", " | Return random integer in range [a, b], including both end points.\n", " | \n", " | randrange(self, start, stop=None, step=1, _int=)\n", " | Choose a random item from range(start, stop[, step]).\n", " | \n", " | This fixes the problem with randint() which includes the\n", " | endpoint; in Python this is usually not what you want.\n", " | \n", " | sample(self, population, k)\n", " | Chooses k unique random elements from a population sequence or set.\n", " | \n", " | Returns a new list containing elements from the population while\n", " | leaving the original population unchanged. The resulting list is\n", " | in selection order so that all sub-slices will also be valid random\n", " | samples. This allows raffle winners (the sample) to be partitioned\n", " | into grand prize and second place winners (the subslices).\n", " | \n", " | Members of the population need not be hashable or unique. If the\n", " | population contains repeats, then each occurrence is a possible\n", " | selection in the sample.\n", " | \n", " | To choose a sample in a range of integers, use range as an argument.\n", " | This is especially fast and space efficient for sampling from a\n", " | large population: sample(range(10000000), 60)\n", " | \n", " | shuffle(self, x, random=None)\n", " | Shuffle list x in place, and return None.\n", " | \n", " | Optional argument random is a 0-argument function returning a\n", " | random float in [0.0, 1.0); if it is the default None, the\n", " | standard random.random will be used.\n", " | \n", " | triangular(self, low=0.0, high=1.0, mode=None)\n", " | Triangular distribution.\n", " | \n", " | Continuous distribution bounded by given lower and upper limits,\n", " | and having a given mode value in-between.\n", " | \n", " | http://en.wikipedia.org/wiki/Triangular_distribution\n", " | \n", " | uniform(self, a, b)\n", " | Get a random number in the range [a, b) or [a, b] depending on rounding.\n", " | \n", " | vonmisesvariate(self, mu, kappa)\n", " | Circular data distribution.\n", " | \n", " | mu is the mean angle, expressed in radians between 0 and 2*pi, and\n", " | kappa is the concentration parameter, which must be greater than or\n", " | equal to zero. If kappa is equal to zero, this distribution reduces\n", " | to a uniform random angle over the range 0 to 2*pi.\n", " | \n", " | weibullvariate(self, alpha, beta)\n", " | Weibull distribution.\n", " | \n", " | alpha is the scale parameter and beta is the shape parameter.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Class methods inherited from Random:\n", " | \n", " | __init_subclass__(**kwargs) from builtins.type\n", " | Control how subclasses generate random integers.\n", " | \n", " | The algorithm a subclass can use depends on the random() and/or\n", " | getrandbits() implementation available to it and determines\n", " | whether it can generate random integers from arbitrarily large\n", " | ranges.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from Random:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from Random:\n", " | \n", " | VERSION = 3\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from _random.Random:\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods inherited from _random.Random:\n", " | \n", " | __new__(*args, **kwargs) from builtins.type\n", " | Create and return a new object. See help(type) for accurate signature.\n", "\n", "FUNCTIONS\n", " betavariate(alpha, beta) method of Random instance\n", " Beta distribution.\n", " \n", " Conditions on the parameters are alpha > 0 and beta > 0.\n", " Returned values range between 0 and 1.\n", " \n", " choice(seq) method of Random instance\n", " Choose a random element from a non-empty sequence.\n", " \n", " choices(population, weights=None, *, cum_weights=None, k=1) method of Random instance\n", " Return a k sized list of population elements chosen with replacement.\n", " \n", " If the relative weights or cumulative weights are not specified,\n", " the selections are made with equal probability.\n", " \n", " expovariate(lambd) method of Random instance\n", " Exponential distribution.\n", " \n", " lambd is 1.0 divided by the desired mean. It should be\n", " nonzero. (The parameter would be called \"lambda\", but that is\n", " a reserved word in Python.) Returned values range from 0 to\n", " positive infinity if lambd is positive, and from negative\n", " infinity to 0 if lambd is negative.\n", " \n", " gammavariate(alpha, beta) method of Random instance\n", " Gamma distribution. Not the gamma function!\n", " \n", " Conditions on the parameters are alpha > 0 and beta > 0.\n", " \n", " The probability distribution function is:\n", " \n", " x ** (alpha - 1) * math.exp(-x / beta)\n", " pdf(x) = --------------------------------------\n", " math.gamma(alpha) * beta ** alpha\n", " \n", " gauss(mu, sigma) method of Random instance\n", " Gaussian distribution.\n", " \n", " mu is the mean, and sigma is the standard deviation. This is\n", " slightly faster than the normalvariate() function.\n", " \n", " Not thread-safe without a lock around calls.\n", " \n", " getrandbits(k, /) method of Random instance\n", " getrandbits(k) -> x. Generates an int with k random bits.\n", " \n", " getstate() method of Random instance\n", " Return internal state; can be passed to setstate() later.\n", " \n", " lognormvariate(mu, sigma) method of Random instance\n", " Log normal distribution.\n", " \n", " If you take the natural logarithm of this distribution, you'll get a\n", " normal distribution with mean mu and standard deviation sigma.\n", " mu can have any value, and sigma must be greater than zero.\n", " \n", " normalvariate(mu, sigma) method of Random instance\n", " Normal distribution.\n", " \n", " mu is the mean, and sigma is the standard deviation.\n", " \n", " paretovariate(alpha) method of Random instance\n", " Pareto distribution. alpha is the shape parameter.\n", " \n", " randint(a, b) method of Random instance\n", " Return random integer in range [a, b], including both end points.\n", " \n", " random() method of Random instance\n", " random() -> x in the interval [0, 1).\n", " \n", " randrange(start, stop=None, step=1, _int=) method of Random instance\n", " Choose a random item from range(start, stop[, step]).\n", " \n", " This fixes the problem with randint() which includes the\n", " endpoint; in Python this is usually not what you want.\n", " \n", " sample(population, k) method of Random instance\n", " Chooses k unique random elements from a population sequence or set.\n", " \n", " Returns a new list containing elements from the population while\n", " leaving the original population unchanged. The resulting list is\n", " in selection order so that all sub-slices will also be valid random\n", " samples. This allows raffle winners (the sample) to be partitioned\n", " into grand prize and second place winners (the subslices).\n", " \n", " Members of the population need not be hashable or unique. If the\n", " population contains repeats, then each occurrence is a possible\n", " selection in the sample.\n", " \n", " To choose a sample in a range of integers, use range as an argument.\n", " This is especially fast and space efficient for sampling from a\n", " large population: sample(range(10000000), 60)\n", " \n", " seed(a=None, version=2) method of Random instance\n", " Initialize internal state from hashable object.\n", " \n", " None or no argument seeds from current time or from an operating\n", " system specific randomness source if available.\n", " \n", " If *a* is an int, all bits are used.\n", " \n", " For version 2 (the default), all of the bits are used if *a* is a str,\n", " bytes, or bytearray. For version 1 (provided for reproducing random\n", " sequences from older versions of Python), the algorithm for str and\n", " bytes generates a narrower range of seeds.\n", " \n", " setstate(state) method of Random instance\n", " Restore internal state from object returned by getstate().\n", " \n", " shuffle(x, random=None) method of Random instance\n", " Shuffle list x in place, and return None.\n", " \n", " Optional argument random is a 0-argument function returning a\n", " random float in [0.0, 1.0); if it is the default None, the\n", " standard random.random will be used.\n", " \n", " triangular(low=0.0, high=1.0, mode=None) method of Random instance\n", " Triangular distribution.\n", " \n", " Continuous distribution bounded by given lower and upper limits,\n", " and having a given mode value in-between.\n", " \n", " http://en.wikipedia.org/wiki/Triangular_distribution\n", " \n", " uniform(a, b) method of Random instance\n", " Get a random number in the range [a, b) or [a, b] depending on rounding.\n", " \n", " vonmisesvariate(mu, kappa) method of Random instance\n", " Circular data distribution.\n", " \n", " mu is the mean angle, expressed in radians between 0 and 2*pi, and\n", " kappa is the concentration parameter, which must be greater than or\n", " equal to zero. If kappa is equal to zero, this distribution reduces\n", " to a uniform random angle over the range 0 to 2*pi.\n", " \n", " weibullvariate(alpha, beta) method of Random instance\n", " Weibull distribution.\n", " \n", " alpha is the scale parameter and beta is the shape parameter.\n", "\n", "DATA\n", " __all__ = ['Random', 'seed', 'random', 'uniform', 'randint', 'choice',...\n", "\n", "FILE\n", " /opt/conda/lib/python3.8/random.py\n", "\n", "\n" ] } ], "source": [ "help(random) # can also show the docstring of a module" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:52:13.621351Z", "start_time": "2020-09-26T10:52:13.615592Z" }, "scrolled": true, "tags": [ "output_scroll", "remove-output" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on _Helper in module _sitebuiltins object:\n", "\n", "class _Helper(builtins.object)\n", " | Define the builtin 'help'.\n", " | \n", " | This is a wrapper around pydoc.help that provides a helpful message\n", " | when 'help' is typed at the Python interactive prompt.\n", " | \n", " | Calling help() at the Python prompt starts an interactive help session.\n", " | Calling help(thing) prints help for the python object 'thing'.\n", " | \n", " | Methods defined here:\n", " | \n", " | __call__(self, *args, **kwds)\n", " | Call self as a function.\n", " | \n", " | __repr__(self)\n", " | Return repr(self).\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", "\n" ] } ], "source": [ "help(help)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**Does built-in functions belong to a module?**" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Indeed, every function must come from a module." ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:53:18.862516Z", "start_time": "2020-09-26T10:53:18.856275Z" }, "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I am from the __builtin__ module.\n" ] } ], "source": [ "__builtin__.print(\"I am from the __builtin__ module.\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "`__builtin__` module is automatically loaded because it provides functions that are commonly use for all programs." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "**How to list everything in a module?** " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "We can use the built-in function `dir` (*directory*)." ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:53:42.536516Z", "start_time": "2020-09-26T10:53:42.526115Z" }, "scrolled": true, "slideshow": { "slide_type": "-" }, "tags": [ "output_scroll", "remove-output" ] }, "outputs": [ { "data": { "text/plain": [ "['ArithmeticError',\n", " 'AssertionError',\n", " 'AttributeError',\n", " 'BaseException',\n", " 'BlockingIOError',\n", " 'BrokenPipeError',\n", " 'BufferError',\n", " 'BytesWarning',\n", " 'ChildProcessError',\n", " 'ConnectionAbortedError',\n", " 'ConnectionError',\n", " 'ConnectionRefusedError',\n", " 'ConnectionResetError',\n", " 'DeprecationWarning',\n", " 'EOFError',\n", " 'Ellipsis',\n", " 'EnvironmentError',\n", " 'Exception',\n", " 'False',\n", " 'FileExistsError',\n", " 'FileNotFoundError',\n", " 'FloatingPointError',\n", " 'FutureWarning',\n", " 'GeneratorExit',\n", " 'IOError',\n", " 'ImportError',\n", " 'ImportWarning',\n", " 'IndentationError',\n", " 'IndexError',\n", " 'InterruptedError',\n", " 'IsADirectoryError',\n", " 'KeyError',\n", " 'KeyboardInterrupt',\n", " 'LookupError',\n", " 'MemoryError',\n", " 'ModuleNotFoundError',\n", " 'NameError',\n", " 'None',\n", " 'NotADirectoryError',\n", " 'NotImplemented',\n", " 'NotImplementedError',\n", " 'OSError',\n", " 'OverflowError',\n", " 'PendingDeprecationWarning',\n", " 'PermissionError',\n", " 'ProcessLookupError',\n", " 'RecursionError',\n", " 'ReferenceError',\n", " 'ResourceWarning',\n", " 'RuntimeError',\n", " 'RuntimeWarning',\n", " 'StopAsyncIteration',\n", " 'StopIteration',\n", " 'SyntaxError',\n", " 'SyntaxWarning',\n", " 'SystemError',\n", " 'SystemExit',\n", " 'TabError',\n", " 'TimeoutError',\n", " 'True',\n", " 'TypeError',\n", " 'UnboundLocalError',\n", " 'UnicodeDecodeError',\n", " 'UnicodeEncodeError',\n", " 'UnicodeError',\n", " 'UnicodeTranslateError',\n", " 'UnicodeWarning',\n", " 'UserWarning',\n", " 'ValueError',\n", " 'Warning',\n", " 'ZeroDivisionError',\n", " '__IPYTHON__',\n", " '__build_class__',\n", " '__debug__',\n", " '__doc__',\n", " '__import__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__spec__',\n", " 'abs',\n", " 'all',\n", " 'any',\n", " 'ascii',\n", " 'bin',\n", " 'bool',\n", " 'breakpoint',\n", " 'bytearray',\n", " 'bytes',\n", " 'callable',\n", " 'chr',\n", " 'classmethod',\n", " 'compile',\n", " 'complex',\n", " 'copyright',\n", " 'credits',\n", " 'delattr',\n", " 'dict',\n", " 'dir',\n", " 'display',\n", " 'divmod',\n", " 'enumerate',\n", " 'eval',\n", " 'exec',\n", " 'execfile',\n", " 'filter',\n", " 'float',\n", " 'format',\n", " 'frozenset',\n", " 'get_ipython',\n", " 'getattr',\n", " 'globals',\n", " 'hasattr',\n", " 'hash',\n", " 'help',\n", " 'hex',\n", " 'id',\n", " 'input',\n", " 'int',\n", " 'isinstance',\n", " 'issubclass',\n", " 'iter',\n", " 'len',\n", " 'license',\n", " 'list',\n", " 'locals',\n", " 'map',\n", " 'max',\n", " 'memoryview',\n", " 'min',\n", " 'next',\n", " 'object',\n", " 'oct',\n", " 'open',\n", " 'ord',\n", " 'pow',\n", " 'print',\n", " 'property',\n", " 'range',\n", " 'repr',\n", " 'reversed',\n", " 'round',\n", " 'runfile',\n", " 'set',\n", " 'setattr',\n", " 'slice',\n", " 'sorted',\n", " 'staticmethod',\n", " 'str',\n", " 'sum',\n", " 'super',\n", " 'tuple',\n", " 'type',\n", " 'vars',\n", " 'zip']" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(__builtin__)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "We can also call `dir` without arguments. \n", "What does it print?" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "ExecuteTime": { "end_time": "2020-09-26T10:53:58.070284Z", "start_time": "2020-09-26T10:53:58.063210Z" }, "scrolled": true, "slideshow": { "slide_type": "-" }, "tags": [ "output_scroll", "remove-output" ] }, "outputs": [ { "data": { "text/plain": [ "['In',\n", " 'Out',\n", " '_',\n", " '_2',\n", " '_23',\n", " '_3',\n", " '_31',\n", " '_4',\n", " '__',\n", " '___',\n", " '__builtin__',\n", " '__builtins__',\n", " '__doc__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__spec__',\n", " '_dh',\n", " '_i',\n", " '_i1',\n", " '_i10',\n", " '_i11',\n", " '_i12',\n", " '_i13',\n", " '_i14',\n", " '_i15',\n", " '_i16',\n", " '_i17',\n", " '_i18',\n", " '_i19',\n", " '_i2',\n", " '_i20',\n", " '_i21',\n", " '_i22',\n", " '_i23',\n", " '_i24',\n", " '_i25',\n", " '_i26',\n", " '_i27',\n", " '_i28',\n", " '_i29',\n", " '_i3',\n", " '_i30',\n", " '_i31',\n", " '_i32',\n", " '_i4',\n", " '_i5',\n", " '_i6',\n", " '_i7',\n", " '_i8',\n", " '_i9',\n", " '_ih',\n", " '_ii',\n", " '_iii',\n", " '_oh',\n", " 'exit',\n", " 'fpow',\n", " 'get_ipython',\n", " 'json',\n", " 'log',\n", " 'm',\n", " 'matplotlib',\n", " 'plt',\n", " 'quit',\n", " 'random',\n", " 'x',\n", " 'yapf_reformat']" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir()" ] } ], "metadata": { "celltoolbar": "Slideshow", "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": false, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false }, "rise": { "enable_chalkboard": true, "scroll": true, "theme": "white" }, "toc": { "base_numbering": 1, "nav_menu": { "height": "195px", "width": "330px" }, "number_sections": true, "sideBar": true, "skip_h1_title": true, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": { "height": "454.418px", "left": "1533px", "top": "110.284px", "width": "243.323px" }, "toc_section_display": true, "toc_window_display": false }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 4 }